package com.sptci.rwt.webui;

import java.util.ArrayList;
import java.util.List;

import com.sptci.echo2.Dimensions;
import com.sptci.echo2.table.ColumnMetaData;
import com.sptci.echo2.table.TableModel;

import com.sptci.rwt.Column;
import com.sptci.rwt.ConnectionManager;
import com.sptci.rwt.QueryExecutor;
import com.sptci.rwt.QueryException;
import com.sptci.rwt.Row;
import com.sptci.rwt.Rows;

/**
 * A custom table model used to display {@link com.sptci.rwt.Rows} object.
 * This is used by the {@link BatchQueryExecutorView} to display each result
 * obtained by executing a statement in the batch specified.
 *
 * <p>&copy; Copyright 2007 Sans Pareil Technologies, Inc.</p>
 * @author Rakesh Vidyadharan 2007-10-12
 * @version $Id: RowsTableModel.java 7 2007-10-21 02:29:50Z rakesh.vidyadharan $
 */
public class RowsTableModel extends TableModel<Row>
{
  /**
   * Create a new instance of the table model using the specified model
   * object.
   *
   * @see #processColumns
   * @param rows The data backing this table model.
   */
  public RowsTableModel( final Rows rows )
  {
    super();
    data.addAll( rows.getRows() );
    processColumns();
  }

  /**
   * Over-ridden to set the proper column meta data using the column
   * information from the row object.
   */
  @Override
  protected void processColumns()
  {
    if ( data.size() == 0 ) return;
    final Row row = data.get( 0 );

    final List<Column> columns = row.getColumns();
    if ( columns.size() == 0 ) return;

    for ( Column column : columns )
    {
      final ColumnMetaData cmd =
        new ColumnMetaData( column.getName(), String.class );
      this.columns.add( cmd );
    }
  }

  /**
   * Return the column name to display at the specified index.
   *
   * @return The name of the column.
   */
  @Override
  public String getColumnName( final int column )
  {
    return columns.get( column ).getName();
  }

  /**
   * Return the value to display at the coordinates specified.
   *
   * @param column The column index.
   * @param row The row index.
   * @return The value for the coordinates.
   * @throws RuntimeException If the indices are invalid.
   */
  @Override
  public Object getValueAt( final int column, final int row )
  {
    if ( column < 0 || column >= getColumnCount() )
    {
      throw new IllegalArgumentException( "Illegal column index: " + column );
    }
    if ( row < 0 || row >= getRowCount() )
    {
      throw new IllegalArgumentException( "Illegal row index: " + row );
    }

    Row r = data.get( row );
    Object value = r.getColumns().get( column ).getContent();
    if ( value instanceof String )
    {
      String text = (String) value;
      if ( text.length() > 50 )
      {
        text = text.substring( 0, 50 );
        text = text.concat( "..." );
      }

      value = text;
    }

    return value;
  }
}
